package client;

import command.client.CommandClient;
import command.client.CommandFactoryClient;
import guiclient.GUIChatPrincipal;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Constants;
import model.MessageCommunication;
import model.User;

public class ClientSession extends Thread {

    private Socket clientSocket;
    private ObjectInputStream input;
    private ObjectOutputStream output;
    private Boolean userActive = true;
    private User user;
    private GUIChatPrincipal principalLogin;

    public ClientSession() {
        try {
            clientSocket = new Socket(Constants.getServerHost(), Constants.getServerPort());
            input = new ObjectInputStream(clientSocket.getInputStream());
            output = new ObjectOutputStream(clientSocket.getOutputStream());
        } catch (IOException ex) {
            Logger.getLogger(ClientSession.class.getName()).log(Level.WARNING,
                    "Hubo un problema al crear la Conexión del Cliente con el Servidor", ex);
        }
    }

    public void setGUIChatPrincipal(GUIChatPrincipal principal) {
        principalLogin = principal;
    }

    public GUIChatPrincipal getGUIChatPrincipal() {
        return principalLogin;
    }

    public ObjectInputStream getObjectInputStream() {
        return input;
    }

    public ObjectOutputStream getObjectOutputStream() {
        return output;
    }

    public User getUserSession() {
        return user;
    }

    public void setUserSession(User u) {
        user = u;
    }

    public void closeSession() {
        userActive = false;
    }

    @Override
    public void run() {
        try {
            while (userActive) {
                MessageCommunication message = (MessageCommunication) input.readObject();
                CommandClient command = CommandFactoryClient.getCommand(message.getMessage());
                command.execute(this, true);
            }
        } catch (ClassNotFoundException | IOException ex) {
            Logger.getLogger(ClientSession.class.getName()).log(Level.WARNING,
                    "Hubo un problema al recibir un comando procedente del servidor", ex);
        } finally {
            if (clientSocket != null) {
                try {
                    clientSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(ClientSession.class.getName()).log(Level.SEVERE,
                            "Fallo al cerrar el Socket del Usuario", ex);
                }
            }
        }
    }
}
